#include "gpio_detect.h"
#include <string.h>


bool isGPIOStateUpdated = false;

typedef enum {
    DEBOUNCE_WAIT,
    DEBOUNCE_STABLE
} DebounceState;


gpio_pair_t state_gpios[MAX_GPIO_NUM] = {
    {GPIOC,GPIO_PIN_12},    //POW-SW-DET
    {GPIOC,GPIO_PIN_11},    //24V-DET
    {GPIOB,GPIO_PIN_13},    //ESTOP
    {GPIOA,GPIO_PIN_0},     //WKUP
    {GPIOA,GPIO_PIN_15},     //FC1
    {GPIOC,GPIO_PIN_10}    //FC2
}; 

static bool state_detect_value[MAX_GPIO_NUM] ={0};

void state_gpio_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    rcu_periph_clock_enable(RCU_GPIOB);
    rcu_periph_clock_enable(RCU_GPIOC);

    for(u8 i=0;i<MAX_GPIO_NUM;i++)
    {
        gpio_mode_set(state_gpios[i].gpio_periph,GPIO_MODE_INPUT, GPIO_PUPD_NONE,state_gpios[i].pin);
    }
}



uint16_t state_gpio_detect_poll_time_count = 0;
void state_gpio_detect_poll(void)
{
    #define DEBOUNCE_DELAY 50

    static u8 state_machine = 0;
    static bool current_state[MAX_GPIO_NUM] = {0};
    static bool stable_state[MAX_GPIO_NUM] = {0};

    switch(state_machine)
    {
        case 0:
        for(u8 i=0;i<MAX_GPIO_NUM;i++)
        {
            current_state[i] = (gpio_input_bit_get(state_gpios[i].gpio_periph,state_gpios[i].pin)==SET);
        }
        state_gpio_detect_poll_time_count = 0;
        state_machine = 1;
        break;

        case 1:
        if(state_gpio_detect_poll_time_count >= DEBOUNCE_DELAY)
        {
            for(u8 i=0;i<MAX_GPIO_NUM;i++)
            {
                stable_state[i] = (gpio_input_bit_get(state_gpios[i].gpio_periph,state_gpios[i].pin)==SET);
            }
            state_machine = 2;
        }
        break;

        case 2:
        for(u8 i=0;i<MAX_GPIO_NUM;i++)
        {
            if(current_state[i] != stable_state[i])
            {
                state_detect_value[i] = current_state[i];
            }
            else
            {
                state_detect_value[i] = stable_state[i];
            }
        }
        state_machine = 3;
        break;

        case 3:
        //added by y.fan on 2025.04.30
        isGPIOStateUpdated = true;

        memset(&current_state,0,sizeof(current_state));
        memset(&stable_state,0,sizeof(stable_state));
        state_machine = 0;
        break;

        default:
        break;
    }
}

bool get_state_value(STATE_GPIO_NAME WHICH_GPIO)
{
    return (bool)state_detect_value[WHICH_GPIO];
}

